import json
import urllib
from urllib import request,parse
from urllib.request import Request

# # 1. 分析请求url
# url = "http://httpbin.org/get?name=qiku"
# # 2. 发起请求
# response = request.urlopen(url)
# # 3. 解析数据
# if response.status == 200:
#     response_bytes = response.read()
#     response_text = response_bytes.decode('utf-8')
#     response_json = json.loads(response_text)
#     print(response_json)
#     print(response_json['headers']['User-Agent'], response_json['args'])



# # 1. 分析请求url
# data = {'name':'qiku','age':'18','addr':'东三街'}
# url_encode = urllib.parse.urlencode(data)
# url = f"http://httpbin.org/get?{url_encode}"
#
# # 1.1 构造请求实例
# req = Request(url, headers={
#     "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36"
# }, method="GET")
#
# # 2. 发起请求
# response = request.urlopen(req)
#
# # 3. 解析数据
# if response.status == 200:
#     response_bytes = response.read()
#     response_text = response_bytes.decode('utf-8')
#     response_json = json.loads(response_text)
#     print(response_json['headers']['User-Agent'], response_json['args'])



# # 1. 分析请求url
# url = "http://httpbin.org/post?name=qiku"
# # 'content-type':"application/x-www-form-urlencoded",
# data = {'age': 10, 'addr': '东三街'}
# url_encode = parse.urlencode(data)
#
# # 1.1 构造请求实例
# req = Request(url, data=url_encode.encode(), headers={
#     "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36",
#     # 默认请求参数的类型form
#     # "content-type":"application/x-www-form-urlencoded",
# }, method="POST")
# # 2. 发起请求 get
# response = request.urlopen(req)
#
# # 3. 解析数据
# if response.status == 200:
#     response_bytes = response.read()
#     response_text = response_bytes.decode('utf-8')
#     response_json = json.loads(response_text)
#     print(response_json, response_json['headers']['User-Agent'], response_json['args'])




# 1. 分析请求url
url = "http://httpbin.org/post?name=qiku"
# 'content-type':"application/x-www-form-urlencoded",
data = {'age': 10, 'addr': '东三街'}
json_encode = json.dumps(data)

# 1.1 构造请求实例
req = Request(url, data=json_encode.encode(), headers={
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36",
    # 更改请求参数的类型form
    "content-type":"application/json",
}, method="POST")
# 2. 发起请求 get
response = request.urlopen(req)

# 3. 解析数据
if response.status == 200:
    response_bytes = response.read()
    response_text = response_bytes.decode('utf-8')
    response_json = json.loads(response_text)
    print(response_json, response_json['headers']['User-Agent'], response_json['args'])